<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Loader;
use think\Cache;
class Wei extends Controller
{
    
   
    public function _empty($name)
    {
        return $this->fetch('/Public/404');
    }
    
    public function newwxzhifu()
    {
            if(!is_weixin()){
                $this->redirect("https://xw.qq.com/");
            }
     
            global $content;
          
            $code    = input("code");
    
    		$state   = input("state");
    		
    		
    		if(empty($code)){
    		     die('缺少参数code,支付配置错误');
    		}
    		
    		if(empty($state)){
    		     die('缺少参数订单号');
    		}
		
	    	$order_info = Cache::store('redis')->get($state);

            
            $out           = $order_info['orderid'];
            $total_fee     = $order_info['money']*100;
            $codehou       = $order_info['code'];
            $userid        = $order_info['userid'];
            $ddh3          = $order_info['ddh3'];
            $uopenid       = $order_info['uopenid'];
            $zyid          = $order_info['zyid'];
            $zftd          = $order_info['zftd'];
            
            
            $is_gongzhong = Db::name('uopenid')->where(['uopenid' => $uopenid])->find();
            
            if($is_gongzhong){
                 die('请重新支付');
            }
            

            $zhifu = Db::name("zhifu")->where(['id' => $order_info['zftd']])->find();
            
            
            $content = unserialize($zhifu['content']);
            
          
            Loader::import('com.wxpay.WxPayPubHelper');
            $jsApi = new \JsApi_pub();
           
            $jsApi->setCode($code);
            $openid = $jsApi->getOpenId();
            
           
            $ts     = check_ts("",$uopenid,"");
            if($ts){
                $this->redirect("/err.html");
            }
            
            
            if(empty($openid) || empty($uopenid)){
             
                 die('缺少必要参数：Openid');
            
            }
           
                
                
            $xieyi = "http://";
           
            $timeStamp = time();
            // $out_trade_no = $content['appid'] . random(4) . "$timeStamp";
            $body = "test";
             $good = array("舒肤佳肥皂2盒装","香皂bai香味持久","男士洗面奶深层清洁","创意夜间照明灯","du搓澡巾清洁","沐浴zhi露持久留香","海飞丝洗发露","梳子","立体两面dao镜子","无味无添加卫生纸","洗zhuan衣粉持久留香","公牛插板1米装","卡通版儿童版雨伞","ins大理石陶瓷杯马克杯子","创意马卡龙儿童3只装牙刷卡通软毛糖果色日系两","304双层不锈钢真空保温杯直身商务水杯子","萃汇尔水性可剥可撕拉指甲油8ml","粉底调色盘美甲用品方形指环","欧丽丝免烤微胶指甲油 3瓶套装","俏夫人大号纸卡装精钢指甲剪刀家居","创意陶瓷卡通马克杯子学生大容量猫咪水杯","跳棋益智玻璃珠飞行棋子","儿童凳子笑脸卡通塑料小凳子 地摊小板凳","20支笔20支笔芯中性笔套装","韩国马卡龙牙刷10支装家用软毛牙刷地摊爆款","双面面板 家用厨房揉面 蒸馒头 多用 砧板","家用扫把簸箕组合套装 家庭清洁用品","1500ml水杯夏季冷水用杯","粮果色不锈钢拉丝修甲六件套","汤勺漏勺不锈钢厨具家用火锅汤勺","时尚化妆镜 PU皮双面镜","双头细轴纸棒棉签棉棒","JGJ喷漆工艺蓝色修甲指甲刀18件套");
            $key = array_rand($good,1);
            $body = $good[$key];
            $unifiedOrder = new \UnifiedOrder_pub();
       
    
            $unifiedOrder->setParameter("openid", "$openid"); //商品描述
            $unifiedOrder->setParameter("body", "$body"); //商品描述
         
            $unifiedOrder->setParameter("out_trade_no", "$out"); //商户订单号 
            $unifiedOrder->setParameter("total_fee", intval($total_fee)); //总金额
            $unifiedOrder->setParameter("notify_url", $xieyi . $content['shename'].url('wxhuidiao')); //通知地址 
            $unifiedOrder->setParameter("trade_type", "JSAPI"); //交易类型
    
            $unifiedOrder->setParameter("attach", "$zftd"); //附加数据
            
         
        
           
            $prepay_id = $unifiedOrder->getPrepayId();
            $jsApi->setPrepayId($prepay_id);
           
            $jsApiParameters = $jsApi->getParameters();
            $this->assign("jsApiParameters", $jsApiParameters);
           
     
            $ename = Cache::store('redis')->get('ylluodi');
    
    
            $tzurl  = "http://" . $ename."/index/index/hezi/?userid=".$order_info['jiami']."&ddh=".$ddh3."&uopenid=".$uopenid;
            $tzurls  = "http://" . $ename."/index/index/shipinok/?zyid=".$zyid."&ddh=".$out."&uopenid=".$uopenid;
          
            $this->assign("userid", $userid);
            
            $this->assign("tzurls", $tzurls);
            $this->assign("tzurl", $tzurl);
           
            return $this->fetch();
        
    }
    
 
    public function wxhuidiao()
    {
        global $content;
       
        Loader::import('com.wxpay.WxPayPubHelper');
        $notify = new \Notify_pub();
        $xml = file_get_contents('php://input');
        
        $notify->saveData($xml);
        
        $zftd  =  $notify->data["attach"];
        $zhifu = Db::name("zhifu")->where(['id' => $zftd])->find();
        $content = unserialize($zhifu['content']);
        
        if ($notify->checkSign() == FALSE)
        {
            $notify->setReturnParameter("return_code", "FAIL"); //返回状态码
            $notify->setReturnParameter("return_msg", "签名失败"); //返回信息
        }
        else
        {
            
             $notify->setReturnParameter("return_code", "SUCCESS"); //设置返回码
             $log_name = "wx.log"; //log文件路径
             $returnXml = $notify->returnXml();
             writefile($log_name, "【接收到的notify通知】:\n" . $xml . "\n");
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;
         
        
        if ($notify->checkSign() == TRUE)
        {
            if ($notify->data["return_code"] == "FAIL")
            {
                writefile($log_name, "【通信出错】:\n" . $xml . "\n");
            }elseif ($notify->data["result_code"] == "FAIL")
            {
                writefile($log_name, "【业务出错】:\n" . $xml . "\n");
            }
            else
            {
                $shijian = date('Y-m-d H:i:s' , time());
                $out_trade_no = $notify->data["out_trade_no"]; //
                $weixin = $notify->data["transaction_id"]; //微信订单号
                $cymoney = $notify->data["total_fee"] / 100;
                $orderNo = $notify->data["out_trade_no"]; //我提交的订单号
                $openid  = $notify->data["openid"];//微信openid
                
                $order = Cache::store('redis')->get($orderNo);
                
                // $order = Db::name("order")->where(['orderid' => $orderNo])->field("userid,zyid,ip,uopenid,orderid")->find();
                
                $userid = $order['userid'];
                
                
                $zyid = $order['zyid'];
                $ip = $order['ip'];
                $ddh = $orderNo;
                $qudao = $ddh;
                $ipz = Db::name("ip")->where(["ddh2" => $ddh])->find();
                if (!empty($ipz))
                {
                    echo "FAIL";
                    exit;
                }
                Db::name("gongyou")->where(['id' => $zyid])->setInc("count"); 
                // Db::name("gongyou")->where(['id' => $zyid])->setInc("rcount");
                if (true)
                {
                    $kl = Db::name("kou")->where(['userid' => $userid])->find();
                    $ns = $kl['ns'];
                    if (!empty($kl))
                    {
                        $cs = $kl['cs'] - 1;
                        if ($cs <= 0)
                        {
                            $shipin = Cache::store('redis')->get('ylgongyou'.$zyid);
                            $zymc = $shipin['name'];
                            $user = Db::name("member")->where(['id' => $userid])->find();
                            $name = $user['nickname'];
                            $data = [];
                            $data['name'] = $name;
                            $data['userid'] = $userid;
                            $data['ddh'] = $ddh;
                            $data['qudao'] = $qudao;
                            $data['money'] = $cymoney;
                            $data['shijian'] = $shijian;
                            $data['zymc'] = $zymc;
                            Db::name("kl")->insert($data);
                            Db::name("kou")->where(['userid' => $userid])->update(['cs' => $ns]);
                            // 不扣量
                            // Db::name("siyou")->where(['id'=>$zyid])->setInc("cs");
                            //  Db::name("gongyou")->where(['id' => $shipin['pid']])->setInc("cs"); 
                            // // //
                            $ddh2 = substr($ddh, 0, 10);
                            $data = [];
                            $data['ip'] = $ip;
                            $data['userid'] = $userid;
                            $data['ddh'] = $ddh2;
                            $data['zyid'] = $zyid;
                            $data['ddh2'] = $ddh;
                            $data['zt'] = "已付";
                            $data['shijian'] = time();
                            $data['openid']  = $openid;
                            
                            // $data['zftd']     = $order['zftd'];
                            $data['uopenid']  = $order['uopenid'];
                           
                           
                            Db::name("ip")->insert($data);
                        }
                        else
                        {
                            Db::name("kou")->where(['userid' => $userid])->setDec("cs"); 
                            // 写自己的数据库
                            $row = Db::name("dingdan")->where(['ddh' => $qudao])->find();
                            if (empty($row))
                            { 
                                // /更新会员金额
                                $user = Db::name("member")->where(['id' => $userid])->find();
                                if (!empty($user))
                                {
                                    if ($cymoney < 1)
                                    {
                                        $money2 = $cymoney;
                                    }
                                    else
                                    {
                                        $money2 = $cymoney - (($cymoney * $user['txfeilv']) / 100);
                                    }
                                    $money = $user['money'] + $money2;
                                    Db::name("member")->where(['id' => $userid])->update(['money' => $money]);
                                }
                                $shipin = Cache::store('redis')->get('ylgongyou'.$zyid);
                                $zymc = $shipin['name'];
                                // if (!empty($shipin))
                                // {
                                //     // Db::name("siyou")->where(['id' => $zyid])->setInc("cs");
                                //     Db::name("gongyou")->where(['id' => $shipin['pid']])->setInc("cs");
                                // }
                                $data = [];
                                $data['zyid'] = $zyid;
                                $data['userid'] = $userid;
                                $data['zymc'] = $zymc;
                                $data['ddh'] = $ddh;
                                $data['money'] = $cymoney;
                                $data['shijian'] = $shijian;
                                $data['wxddh'] = $weixin;
                                Db::name("dingdan")->insert($data);
                                $ddh2 = substr($ddh, 0, 10);
                                $data = [];
                                $data['ip'] = $ip;
                                $data['userid'] = $userid;
                                $data['ddh'] = $ddh2;
                                $data['zyid'] = $zyid;
                                $data['ddh2'] = $ddh;
                                $data['zt'] = "已付";
                                $data['shijian'] = time();
                                $data['openid']  = $openid;
                                // $data['zftd']     = $order['zftd'];
                                $data['uopenid']  = $order['uopenid'];
                           
                                Db::name("ip")->insert($data);
                            } 
                            // 写自己的数据库
                        } 
                        // 不扣量
                        // 代理ID没添加扣量参数
                    }
                    else
                    { 
                        // 写自己的数据库
                        $row = Db::name("dingdan")->where(['ddh' => $qudao])->find();
                        if (empty($row))
                        { 
                            // /更新会员金额
                            $user = Db::name("member")->where(['id' => $userid])->find();
                            if (!empty($user))
                            {
                                if ($cymoney < 1)
                                {
                                    $money2 = $cymoney;
                                }
                                else
                                {
                                    $money2 = $cymoney - (($cymoney * $user['txfeilv']) / 100);
                                }
                                $money = $user['money'] + $money2;
                                Db::name("member")->where(['id' => $userid])->update(['money' => $money]);
                            }
                            $shipin = Cache::store('redis')->get('ylgongyou'.$zyid);
                            $zymc = $shipin['name'];
                            
                            $data = [];
                            $data['zyid'] = $zyid;
                            $data['userid'] = $userid;
                            $data['zymc'] = $zymc;
                            $data['ddh'] = $ddh;
                            $data['money'] = $cymoney;
                            $data['shijian'] = $shijian;
                            $data['wxddh'] = $weixin;
                            Db::name("dingdan")->insert($data);
                            $ddh2 = substr($ddh, 0, 10);
                            $data = [];
                            $data['ip'] = $ip;
                            $data['userid'] = $userid;
                            $data['ddh'] = $ddh2;
                            $data['zyid'] = $zyid;
                            $data['ddh2'] = $ddh;
                            $data['zt'] = "已付";
                            $data['shijian'] = time();
                            $data['openid']  = $openid;
                            // $data['zftd']     = $order['zftd'];
                            $data['uopenid']  = $order['uopenid'];
                            
                            Db::name("ip")->insert($data);
                        } 
                        // 写自己的数据库
                    } 
                    // 代理ID没添加扣量参数
                    // 扣量开关关闭
                }
                else
                {
                    $row = Db::name("dingdan")->where(['ddh' => $qudao])->find();
                    if (empty($row))
                    { 
                        // /更新会员金额
                        $user = Db::name("member")->where(['id' => $userid])->find();
                        if (!empty($user))
                        {
                            if ($cymoney < 1)
                            {
                                $money2 = $cymoney;
                            }
                            else
                            {
                                $money2 = $cymoney - (($cymoney * $user['txfeilv']) / 100);
                            }
                            $money = $user['money'] + $money2;
                            Db::name("member")->where(['id' => $userid])->update(['money' => $money]);
                        }
                        $shipin = Cache::store('redis')->get('ylgongyou'.$zyid);
                        $zymc = $shipin['name'];
                       
                        $data = [];
                        $data['zyid'] = $zyid;
                        $data['userid'] = $userid;
                        $data['zymc'] = $zymc;
                        $data['ddh'] = $ddh;
                        $data['money'] = $cymoney;
                        $data['shijian'] = $shijian;
                        $data['wxddh'] = $weixin;
                        Db::name("dingdan")->insert($data);
                        $ddh2 = substr($ddh, 0, 10);
                        $data = [];
                        $data['ip'] = $ip;
                        $data['userid'] = $userid;
                        $data['ddh'] = $ddh2;
                        $data['zyid'] = $zyid;
                        $data['ddh2'] = $ddh;
                        $data['zt'] = "已付";
                        $data['shijian'] = time();
                        $data['openid']  = $openid;
                        // $data['zftd']     = $order['zftd'];
                        $data['uopenid']  = $order['uopenid'];
                        
                        Db::name("ip")->insert($data);
                    } 
                    // 写自己的数据库
                }
            
		      return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';

                // 扣量开关关闭
            }
            
            
            
            
            
            
            
        }
    }
    
}